
const fs = require('fs');
const path = require('path');

const clientFilePath = path.resolve(__dirname, '../../client/client.js');

const clientPublicPath = `/vite/client`;

function clientPlugin(context) {
  const { app, port } = context;

  const clientCode = fs.readFileSync(clientFilePath, 'utf-8').replace('__HMR_SERVER_PORT__', port);

  app.use(async (ctx, next) => {
    if (ctx.path === clientPublicPath) {
      ctx.type = 'js'
      ctx.status = 200
      ctx.body = clientCode
    } else {
      return next()
    }
  })
}

module.exports = {
  clientFilePath,
  clientPublicPath,
  clientPlugin,
}